from loguru import logger
from contextvars import ContextVar
import random

# 用于在每个并发/异步上下文（如请求、协程、线程）中独立存储和获取信息
_trace_id: ContextVar[str] = ContextVar('x_trace_id', default="")
_lane_code: ContextVar[str] = ContextVar('x_lane_code', default="")


# def _logger_filter_info_only(record):
#     return record["level"].name == "INFO"
#
#
# def _logger_filter_error_only(record):
#     return record["level"].name == "ERROR"
#
#
# def _logger_filter_warn_only(record):
#     return record["level"].name == "WARNING"


# def json_format(record):
#     '''
#     将日志输出格式化为json格式
#     :param record:
#     :return:
#     '''
#     record["extra"]["serialized"] = serialize(record)
#     return "{extra[serialized]}\n"


# def init_log_path(log_path):
#     if not os.path.exists(log_path):
#         os.makedirs(log_path)
#
# if os.environ.get('env') == 'prd':
#     log_path = '/xx/logs/app'
# else:
#     log_path = os.path.abspath(os.path.join(__file__, '../../../xx/logs/app'))
# init_log_path(log_path)

# 日志输出的文件格式
# 配置INFO级别的日志文件
# logger.add(log_path + "/INFO.{time:YYYY-MM-DD}.log",
#            level="INFO", rotation="00:00", retention="5 days", enqueue=True,
#            filter=_logger_filter_info_only, format=json_format, watch=True)
# # 配置WARN级别的日志文件
# logger.add(log_path + "/WARN.{time:YYYY-MM-DD}.log",
#            level="WARNING", rotation="00:00", retention="5 days", enqueue=True,
#            filter=_logger_filter_warn_only, format=json_format, watch=True)
# # 配置ERROR级别的日志文件
# logger.add(log_path + "/ERROR.{time:YYYY-MM-DD}.log",
#            level="ERROR", rotation="00:00", retention="5 days", enqueue=True,
#            filter=_logger_filter_error_only, format=json_format, watch=True)


# TraceID处理
class TraceID:
    @staticmethod
    def set_trace(id: str, title: str = "task") -> ContextVar[str]:
        """设置全链路追踪ID
        Returns:
            ContextVar[str]: _description_
        """
        id = f"{id}"
        _trace_id.set(id)
        return _trace_id

    @staticmethod
    def get_trace():
        return _trace_id.get()


# LaneCode处理
class LaneCode:
    @staticmethod
    def set_lane_code(code: str, title: str = "task") -> ContextVar[str]:
        """设置全链路追踪ID
        Returns:
            ContextVar[str]: _description_
        """
        id = f"{code}"
        _lane_code.set(code)
        return _lane_code

    @staticmethod
    def get_lane_code():
        return _lane_code.get()


def generate_trace_id():
    # 生成一个随机的16位十六进制字符串作为 Trace ID
    trace_id = ''.join(random.choice('0123456789abcdef') for i in range(16))
    return trace_id


def get_logger():
    return logger
